package com.lys.conf;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * 监听事件、数据存在回滚、获取到数据回滚、最后结果
 */
public class CallbackWatcher implements Watcher, AsyncCallback.StatCallback, AsyncCallback.DataCallback {
    private ZooKeeper zooKeeper;// 连接对象
    private MyConfig myConfig;// 需要取出的配置对象
    private CountDownLatch countDownLatch;// 用来协调线程

    public MyConfig getMyConfig() {
        return myConfig;
    }

    public void setZooKeeper(ZooKeeper zooKeeper) {
        this.zooKeeper = zooKeeper;
    }

    /*
     * 节点监听事件
     */
    @Override
    public void process(WatchedEvent event) {
        System.out.println("Watcher执行了");
        Event.EventType type = event.getType();
        switch (type) {
            case None:
                break;
            case NodeCreated:
                zooKeeper.getData("/testConfig",this,this,"abc");
                break;
            case NodeDeleted:
                myConfig = null;
                break;
            case NodeDataChanged:
                zooKeeper.getData("/testConfig",this,this,"abc");
                break;
            case NodeChildrenChanged:
                break;
//            case DataWatchRemoved:
//                break;
//            case ChildWatchRemoved:
//                break;
//            case PersistentWatchRemoved:
//                break;
        }
    }
    /*
     * 节点是否存在的回滚事件
     */
    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        System.out.println("exists回滚函数执行了");
        if (stat!=null) {
            zooKeeper.getData("/testConfig",this,this,"abc");
        }
    }
    /*
     * 获取节点数据的回滚事件
     */
    @Override
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        System.out.println("getData回滚函数执行了");
        myConfig = new MyConfig();
        myConfig.setConfig(new String(data));
        countDownLatch.countDown();
    }
    /*
     * 封装方法，获取MyConfig
     */
    public void initConfig(String path){
        countDownLatch = new CountDownLatch(1);
        zooKeeper.exists(path,this,this,"abc");

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
